package com.hmjk.health.background.data;

import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.text.format.Time;
import android.util.Log;

import com.hmjk.health.HealthApp;
import com.hmjk.health.background.DataManager;
import com.hmjk.health.background.DatabaseHelper;
import com.hmjk.health.background.NetService;
import com.hmjk.health.util.ACareReminder;
import com.hmjk.health.util.AReminder;
import com.hmjk.health.util.LOCATION_INFO;
import com.hmjk.health.util.ReminderList;

public class CareReminderUpdated extends DataUpdated{
	private static String TAG = CareReminderUpdated.class.getSimpleName();
	//public static final String TYPE_FAMILY = "family";
	//public static final String TYPE_USER = "user";
	//public static final String TYPE_ALL = "all";
	private boolean working = false;	
	private static HashMap<String,ReminderList> mMap = new HashMap<String,ReminderList>();
	
	private void logd(String info){
		Log.d(TAG, info);
	}
	
	public CareReminderUpdated(HealthApp app, DataManager dm) {
		super(app, dm);
		UPDATE_TIME = 2 * 60 * 1000;
	}

	@Override
	public void setUserData(Object data) {
		// TODO Auto-generated method stub
		reqTime = 0;
	}

	@Override
	public long delay() {
      return -1;
	}
	
	private void doRequest(String uid,String tid,int devtype,int index){		//index = -1 get all
		Intent si = new Intent(NetService.GET_DATA_ACTION);
		si.putExtra("sub_act", NetService.GET_CARE_REMINDER);
		si.putExtra("uid", uid);
		si.putExtra("tid", tid);
		si.putExtra("terminaltype",  Integer.toString(devtype));
		if(index != -1)
		  si.putExtra("dex", AReminder.int2HexStr(index));
		else
		  si.putExtra("dex", AReminder.int2HexStr(index));
		
		Time t = new Time();
		t.setToNow();
		String stamp = "GET_CARE_REMINDER" + t.toString(); 
		si.putExtra("stamp",stamp);
		working = true;
		mApp.addNetHandler(stamp,mDm.getBackGroundHandler());
		mApp.startService(si);
	}

	@Override
	public boolean grab() {
		return false;
	}

	@Override
	public boolean grabByUser() {
		return false;
	}
	
	@Override
	public boolean grabByUserWithSingleArgs(Object args){		
		if(args == null)
			return false;
		
		String tid = (String)args;
		if(tid.trim().isEmpty())
			return false;
		
		String uid = mApp.getUID();
		logd("grabByUserWithSingleArgs uid="+uid);
		if(uid == null)
			return false;
		
		if(working){
			logd("grabByUserWithSingleArgs downloading");
			return false;
		}
				
		long curMs = System.currentTimeMillis();
		logd("grabByUserWithSingleArgs curMs="+curMs+" reqTime="+reqTime);
		if((curMs - reqTime) > 10 * 1000){
		doRequest(uid, tid,0,255);
			reqTime = curMs;
			logd("grabByUserWithSingleArgs req sent!");
			return true;
		}
		return false;
	}	
	
	private void updateReminderInList(ACareReminder rem)
	{
		ReminderList list =  mMap.get(rem.tid);
		if(list == null)
		{
			ReminderList  ls = new ReminderList();
			ls.addAReminder(rem);
			mMap.put(rem.tid, ls);
		}
		else
		{
			int pos = -1;
			
			for(int i =0; i<list.getReminderList().size();i++){				
				AReminder r = list.getReminder(i);				
				if(r.Index == rem.Index)
				{
					pos = i;
					break;
				}               
			}   //found position
			
			if(pos == -1)
				list.addAReminder(rem);
			else
			{
				list.getReminderList().remove(pos);
				list.getReminderList().add(pos, rem);
			}
		}
	}
	
	private void delReminderInList(ACareReminder rem)
	{
		ReminderList list =  mMap.get(rem.tid);
		if(list != null)
		{
		int pos = -1;
		
		for(int i =0; i<list.getReminderList().size();i++){				
			AReminder r = list.getReminder(i);				
			if(r.Index == rem.Index)
			{
				pos = i;
				break;
			}               
		}   //found position
		
		if(pos != -1)
		{
			list.getReminderList().remove(pos);
		}	
		}
	}

	@Override
	public void receive(String stamp, String sjson) {
		if(stamp.startsWith("GET_CARE_REMINDER")){
			if(sjson != null){
				int code = 400;
				String state = "af";
				boolean update = false;
				try {
					JSONObject json = new JSONObject(sjson);
					code = json.getInt("code");
					if(code == 200){
						state = json.getString("state");
						if(state.equalsIgnoreCase("00")){
							JSONObject recdata = json.getJSONObject("recdata");
							JSONObject senddata = json.getJSONObject("senddata");
							String tid = senddata.getString("tid");
						    int devtype = Integer.parseInt(senddata.getString("terminaltype"));
						    
							if(recdata != null){
								upTime = System.currentTimeMillis();
								//mMap.clear();
								if(recdata.has("remindarr")){
									JSONArray arr = recdata.getJSONArray("remindarr");
									int size = arr.length();
									for(int i = 0; i < size; i++){
										JSONObject o = arr.getJSONObject(i);
										ACareReminder d = new ACareReminder(tid,devtype);
										d.Index = Integer.parseInt(o.getString("dex"), 16);
										d.isopen = Integer.parseInt(o.getString("isopen"));
										d.time.setByHexStr(o.getString("remind"));
										String remode = o.getString("remindmode");
										//if(null == remode)
										//	d.remind_mode = 2;
										//else
										//    d.remind_mode = Integer.parseInt(o.getString("remindmode"));
										d.setTip(o.getString("remindmsg"));
										d.update_time = o.getLong("updatetime");
										updateReminderInList(d);
										}

									}
								update = true;
								}
							}
						}
				}catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				Intent i = new Intent(DataManager.DATA_UPDATE_ACTION);
				i.putExtra("type",DataManager.F_CARE_REMINDER);
				i.putExtra("update", update);
				i.putExtra("state", state);
				mApp.sendBroadcast(i);
				working = false;
			}
		}else if(stamp.startsWith("COMMIT_CARE_REMINDER")){
			if(sjson != null){
				String state = "af";
				String tid = null;
				int code = 400;
				try {
					JSONObject json = new JSONObject(sjson);
					code = json.getInt("code");
					JSONObject sd = json.getJSONObject("senddata");
					  tid = sd.getString("tid");
					
					if(code == 200){
						state = json.getString("state");
						if(state.equalsIgnoreCase("00")){
							
							int devType = Integer.parseInt(sd.getString("terminaltype"));
							int opt = Integer.parseInt(sd.getString(("opt")), 16);
							
							String timeS = sd.getString("remind");
							String tip = sd.getString("remindmsg");

                            ACareReminder rem = new ACareReminder(tid,devType);

                            rem.update_time = sd.getLong("updatetime");
                            rem.time.setByHexStr(timeS);
                            rem.setTip(tip);
                            //rem.remind_mode = Integer.parseInt(sd.getString("remindmode"));
                            int dex; 
                            if(opt == AReminder.NEW_OPEN_OP || opt == AReminder.NEW_OFF_OP)
                            {
                            	JSONObject recdata = json.getJSONObject("recdata");
                            	dex = Integer.parseInt(recdata.getString(("dex")), 16);
                            }
                            else
                            {
                            	dex = Integer.parseInt(sd.getString(("dex")), 16);
                            }
                            rem.setIndex(dex);
                            
                            if(opt == AReminder.NEW_OPEN_OP || opt == AReminder.MODIFY_OPEN_OP)
                            {
                            	rem.isopen = 0;
                            	updateReminderInList(rem);
                            }
                            else if(opt == AReminder.NEW_OFF_OP || opt == AReminder.MODIFY_OFF_OP)
                            {
                            	rem.isopen = 1;
                            	updateReminderInList(rem);
                            }
                            else
                            {
                            	delReminderInList(rem);        
                            }

					}
				}
				}catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					state = "af";
				}
				Intent i = new Intent(DataManager.DATA_COMMIT_RESULT);
				i.putExtra("type",DataManager.F_CARE_REMINDER);
				i.putExtra("tid", tid);
				i.putExtra("state", state);
				i.putExtra("code", code);
				mApp.sendBroadcast(i);
			}
		}
		
	}
	
	@Override
	public Object check(String[] arg) {
		if((arg != null) && (arg.length > 0)){
			
			String tid = arg[0];
			ReminderList list = mMap.get(tid);
			return list;
		}
		return null;
	}

	@Override
	public boolean commit(Object data) {
		ACareReminder rem = (ACareReminder)data;
		
		Intent si = new Intent(NetService.COMMIT_DATA_ACTION);
		si.putExtra("sub_act", NetService.COMMIT_CARE_REMINDER);
		
		
		si.putExtra("uid", mApp.getUID());
        si.putExtra("tid", rem.tid);
        si.putExtra("terminaltype", Integer.toString(rem.devType));
        si.putExtra("opt", AReminder.int2HexStr(rem.opt));
        si.putExtra("dex", AReminder.int2HexStr(rem.Index));
        si.putExtra("remind", rem.time.getHexStr());
        si.putExtra("remindmsg", rem.tipContent);
        si.putExtra("updatetime", System.currentTimeMillis());
        si.putExtra("remindmode",Integer.toString(2));
		
		Time t = new Time();
		t.setToNow();
		String stamp = "COMMIT_CARE_REMINDER" + t.toString(); 
		si.putExtra("stamp",stamp);
		mApp.addNetHandler(stamp,mDm.getBackGroundHandler());
		mApp.startService(si);
		return true;
	}

	@Override
	public void release() {
		// TODO Auto-generated method stub
		
	}
}
